package com.czh.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.czh.domain.ResponseResult;
import com.czh.domain.dto.QueryCategoryDto;
import com.czh.domain.entity.Category;
import com.czh.domain.vo.CategoryVo;
import com.czh.domain.vo.CategoryPageVo;
import com.czh.domain.vo.ExcelCategoryVo;
import com.czh.enums.AppHttpCodeEnum;
import com.czh.service.CategoryService;
import com.czh.utils.BeanCopyUtils;
import com.czh.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 分类管理控制器
 */
@RestController
@RequestMapping("/content/category")
public class CategoryManageController {
    @Autowired
    private CategoryService categoryService;
    /**
     * 用在写博客界面展示分类列表
     */
    @GetMapping("/listAllCategory")
    public ResponseResult<List<CategoryVo>> listAllCategory(){
        return categoryService.listAllCategory();
    }
    /**
     * 用在分类管理展示分类列表
     */
    @GetMapping("/list")
    public ResponseResult<CategoryPageVo> getCategoryList(Integer pageNum, Integer pageSize, QueryCategoryDto queryCategoryDto){
         return categoryService.getCategoryPageList(pageNum,pageSize, queryCategoryDto);
    }
    //导出分类为Excel
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("分类.xlsx",response);
            //获取需要导出的数据
            List<Category> categoryVos = categoryService.list();

            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryVos, ExcelCategoryVo.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(excelCategoryVos);

        } catch (Exception e) {
            ResponseResult<Object> result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }
    @PostMapping
    public ResponseResult<Object> addCategory(@RequestBody Category category){
        return categoryService.addCategory(category);
    }
    @DeleteMapping("/{id}")
    public ResponseResult<Object> deleteCategory(@PathVariable("id") Long id){
        return categoryService.deleteCategory(id);
    }
    //修改分类填充信息
    @GetMapping("/{id}")
    public ResponseResult<CategoryVo> getCategoryById(@PathVariable("id") Long id){
        return categoryService.getCategoryById(id);
    }
    @PutMapping
    public ResponseResult<Object> updateCategory(@RequestBody Category category){
        return categoryService.updateCategory(category);
    }
}
